package org.csu.mypetstore.api.controller.front;

import jakarta.servlet.http.HttpServletRequest;
import org.csu.mypetstore.api.common.CommonResponce;
import org.csu.mypetstore.api.common.JwtTokenUtil;
import org.csu.mypetstore.api.entity.OrderRequest;
import org.csu.mypetstore.api.service.OrderService;
import org.csu.mypetstore.api.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@CrossOrigin(origins = "http://localhost:8888",
        allowedHeaders = "*",
        methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS},
        allowCredentials = "true")
@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public CommonResponce<OrderVO> createOrder(
            @RequestHeader("Authorization") String token,
            @RequestBody OrderRequest orderRequest) {
        try{
            String username = jwtTokenUtil.getUsernameFromToken(token.replace("Bearer ", ""));
            return orderService.createOrder(username, orderRequest);
        } catch (Exception e) {
            return CommonResponce.createForError(1,"服务器异常");
        }
    }

    @GetMapping("/{orderId}")
    public CommonResponce<OrderVO> getOrder(
            @PathVariable String orderId,
            @RequestHeader("Authorization") String token) {
        try{
            String username = jwtTokenUtil.getUsernameFromToken(token.replace("Bearer ", ""));
            return orderService.getOrder(username, orderId);
        } catch (Exception e) {
            return CommonResponce.createForError(1,"服务器异常");
        }
    }

    @GetMapping("/order/{userId}")
    public CommonResponce<List<OrderVO>> getOrders(@RequestHeader("Authorization") String token) {
        try{
            String username = jwtTokenUtil.getUsernameFromToken(token.replace("Bearer ", ""));
            return orderService.getOrders(username);
        } catch (Exception e) {
            return CommonResponce.createForError(1,"服务器异常");
        }
    }

}
